# encoding: utf-8

"""Discuz! X3.2会员批量注册脚本

@author SparkLee <liweijsj@163.com>
@since  2016/10/28 11:00

注：urllib2是python2中的模块，python3中无此模块，故执行此脚本需要python2
"""

import urllib        # 通过URL请求网络数据 - Open arbitrary resources by URL
import urllib2       # urllib的扩展库 -  extensible library for opening URLs
import cookielib     # 处理cookie - Classes for automatic handling of HTTP cookies
import re            # 处理正则表达式 - Regular expression operations
import time          # 处理时间
import random        # 处理随机数

from xpinyin import Pinyin # 中文转英文的第三方包

class Adder(object):
    cnt_success = 0     # 添加成功的用户数
    cnt_fail = 0        # 添加失败的用户数

    home_url = ''
    admin_user = ''
    admin_password = ''
    formhash = ''

    def __init__(self, host, url, admin_user, admin_password):
        """构造函数
        """

        self.home_url = url + "?"
        self.admin_user = admin_user
        self.admin_password = admin_password
        self.cookieJar=cookielib.CookieJar() # 初始化一个CookieJar来处理Cookie
        self.opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookieJar)) # 实例化一个全局opener
        self.headers = {
            "Host": host, 
            "Referer": url
        }

    def login(self):        
        # 登陆管理后台
        data={
            "admin_username":self.admin_user,
            "admin_password":self.admin_password,
            'frames':'yes',
            'admin_questionid':'0',
            'submit':'提交'
        }
        post_data=urllib.urlencode(data)
        url = self.home_url
        req=urllib2.Request(url,post_data,self.headers)
        result = self.opener.open(req)

        # 打开管理后台"添加用户"界面
        url = self.home_url+'action=members&operation=add'
        req=urllib2.Request(url)
        result = self.opener.open(req)
        tpage = result.read()

        # 获取"添加用户"界面表单元素formhash的值，此值在提交用户表单时会用到
        i = tpage.find('<input type="hidden" name="formhash" value="')
        tpage = tpage[i:100+i]
        pattern = re.compile(r'<input type="hidden" name="formhash" value="(\w+)" />')
        match = pattern.match(tpage)
        formhash = ''
        if match:
            formhash = match.groups()[0]
        self.formhash = formhash

    def adduser(self,uname,upwd,uemail,ugrpid = '10',emailnotify = '0',addsubmit = '提交'):
        """注册新用户
        """
        
        url = ""
        url = self.home_url+('action=members&operation=add')
        values = {
            'formhash':self.formhash,
            'newusername':uname,
            'newpassword':upwd,
            'newemail':uemail,
            'newgroupid':ugrpid,
            'emailnotify':emailnotify,
            'addsubmit':addsubmit
        }
        data = urllib.urlencode(values) 
        req=urllib2.Request(url,data,self.headers)
        response = self.opener.open(req)
        the_page = response.read()

        i = the_page.find('<h3>Discuz! 提示</h3><div class="infobox"><h4 class="infotitle2">用户')
        if (i>0):
            self.cnt_success += 1
            print(("用户"+uname+"添加成功！").decode("utf8"))
        else:
            self.cnt_fail += 1
            print(("用户"+uname+"添加失败！").decode("utf8"))

    def addusers(self,users):
        """批量注册新用户

        users参数的格式为：
        [
            {   
                'newusername':newusername,
                'newpassword':newpassword,
                'newemail':newemail,
                'newgroupid':'10',
                'emailnotify':'0',
                'addsubmit':'addsubmit'
            },
            ....
        ]
        """

        # 登陆管理后台
        self.login()

        # 批量注册新用户
        for u in users: 
            if (hasattr(u, "newgroupid") and hasattr(u, "emailnotify") and hasattr(u, "addsubmit")) :
                self.adduser(u['newusername'], u['newpassword'], u['newemail'], u['newgroupid'], u['emailnotify'], u['addsubmit'])
            else:
                self.adduser(u['newusername'], u['newpassword'], u['newemail'])

        print(('待添加总用户数：' + str(len(users))).decode("utf8"))
        print(('添加成功用户数：' + str(self.cnt_success)).decode("utf8"))
        print(('添加失败用户数：' + str(self.cnt_fail)).decode("utf8"))

def readtxt(file):
    """从文件中读取待注册用户数据
    """

    pinyin = Pinyin()
    users = []
    fo = open(file)
    lines = fo.readlines()
    for l in lines:
        if len(l)>0 :
            u = l.split(",")
            if len(u) == 6:
                users.append({
                    'newusername':u[0],
                    'newpassword':u[1],
                    'newemail':u[2],
                    'newgroupid':u[3],
                    'emailnotify':u[4],
                    'addsubmit':u[5]                               
                })
            if len(u) == 3:
                users.append({
                    'newusername':u[0],
                    'newpassword':u[1],
                    'newemail':u[2]                            
                }) 
            if len(u) == 1:
                npassword = 'zjito123bbs'

                # 生成随机（唯一）的邮箱地址
                # nemail = pinyin.get_initials(unicode(u[0],'utf-8'), u'').lower() # 若中文用户名中有@等特殊符号，则不适合用于邮箱地址，故暂时不用此种方法
                timestr = str(time.time()).replace('.', '')[-4:] # 取当前时间（去掉点）的后四位
                rand1 = random.randint(1, 99)
                rand2 = random.randint(99, 999)
                if rand1 < 10:
                    suffix = '@163.com'
                if rand1 >= 10 and rand1 < 20:
                    suffix = '@qq.com'
                if rand1 >= 20 and rand1 < 30:
                    suffix = '@gmail.com'
                if rand1 >= 20 and rand1 < 30:
                    suffix = '@sina.com'
                if rand1 >= 30 and rand1 < 40:
                    suffix = '@21cn.com'
                if rand1 >= 40:
                    suffix = '@126.com'
                nemail = ''.join([str(rand1), timestr, str(rand2), suffix])

                users.append({
                    'newusername':u[0],
                    'newpassword':npassword,
                    'newemail':nemail
                })
    return users  

def main():
    file = 'user.txt'
    host = 'bbs.zjito.com'
    home_url = 'http://' + host + '/admin.php'
    admin = 'admin'
    pwd = '111111'
    adder = Adder(host, home_url,admin,pwd) 
    users = readtxt(file)
    adder.addusers(users)

if __name__ == '__main__':
    main()
    pass

